#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>
// for open
#include <fcntl.h>
// for iov
#include <sys/uio.h>

void send_fd(int sock, int fd)
{
    struct iovec iov[1];
    char c = 0;
    iov[0].iov_base = &c;
    iov[0].iov_len  = 1;

    int cmsgsize = CMSG_LEN(sizeof(int));
    struct cmsghdr* cmptr = (struct cmsghdr*)malloc(cmsgsize);
    if(cmptr == NULL){
        exit(1);
    }
    cmptr->cmsg_level = SOL_SOCKET;
    cmptr->cmsg_type = SCM_RIGHTS; // we are sending fd.
    cmptr->cmsg_len = cmsgsize;

    struct msghdr msg;
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;
    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_control = cmptr;
    msg.msg_controllen = cmsgsize;
    *(int *)CMSG_DATA(cmptr) = fd;

    int ret = sendmsg(sock, &msg, 0);
    free(cmptr);
    if (ret == -1){
        exit(1);
    }
}

int recv_fd(int sock)
{
    int cmsgsize = CMSG_LEN(sizeof(int));
    struct cmsghdr* cmptr = (struct cmsghdr*)malloc(cmsgsize);

    char buf[32]; // the max buf in msstruct g.
    struct iovec iov[1];
    iov[0].iov_base = buf;
    iov[0].iov_len = sizeof(buf);

    struct msghdr msg;
    msg.msg_iov = iov;
    msg.msg_iovlen  = 1;
    msg.msg_name = NULL;
    msg.msg_namelen = 0;
    msg.msg_control = cmptr;
    msg.msg_controllen = cmsgsize;

    int ret = recvmsg(sock, &msg, 0);
    free(cmptr);
    if (ret == -1) {
        exit(1);
    }

    int fd = *(int *)CMSG_DATA(cmptr);
    return fd;
}

void master_process_cycle(int fds[2]){

    // master use fds[0], and close fds[1]
    int fd = fds[0];
    //close(fds[1]);
    //cout << "channel: #" << fds[0] << ", #" << fds[1] << ", fd=#" << fd << endl;

    // send file discriptor
    system("rm -f /home/winlin/1.txt");
    int file = open("/home/winlin/1.txt", O_CREAT|O_TRUNC|O_RDWR);
    send_fd(fd, file);
    close(file);

    int status;
    waitpid(-1, &status, 0);
    exit(0);
}

void worker_process_cycle(int fds[2]){

    // master use fds[1], and close fds[0]
    int fd = fds[1];
    //close(fds[0]);
    //cout << "channel: #" << fds[0] << ", #" << fds[1] << ", fd=#" << fd << endl;

    int file = recv_fd(fd);
    printf("收到了");
    if(file < 0){
        exit(1);
    }
    char msg[] = "child process";
    close(file);

    exit(0);
}

// <<Unix高级环境编程>> 第17.4节程序
int main(int argc, char** argv){
//    cout << "current pid: " << getpid() << endl;

    int fds[2];
    if(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1){
//        cout << "failed to create domain socket by socketpair" << endl;
        exit(1);
    }
//    cout << "create domain socket by socketpair success" << endl;
//
//    cout << "create progress to communicate over domain socket" << endl;
    pid_t pid = fork();
    if(pid == 0){
        worker_process_cycle(fds);
    }
    else{
        master_process_cycle(fds);
    }

    for(;;){
        pause();
    }
}
